package com.senior.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerDemo {

    private static final int SIZE = 50;

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch downLatch = new CountDownLatch(50);
        MyNumber myNumber = new MyNumber();
        for (int i = 0; i < SIZE; i++) {//开50个线程，每个线程进行1000次原子自增
            new Thread(()->{
                try {
                    for (int j = 0; j <1000 ; j++) {
                        myNumber.addPlusPlus();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    downLatch.countDown();
                }

            },"线程"+i+"  ").start();
        }
        downLatch.await(); //我们发现睡眠时间不准确，不知道要睡多久，所以我们用CountDownLatch，让所以线程计算完成，然后才执行下面的
        //TimeUnit.SECONDS.sleep(5);//睡5秒原因是防止main线程太快，上面的50个线程没计算完，得出不正确的结果
        System.out.println(Thread.currentThread().getName() + "\t" + "---result:" + myNumber.atomicInteger.get());
    }
}

class MyNumber{

    AtomicInteger atomicInteger = new AtomicInteger();

    public void addPlusPlus(){
        atomicInteger.incrementAndGet();//原子上增加一个当前值
    }
}
